package com.ruoyi.web.controller.system;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.SysWxUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.community.service.ISysCommunityService;
import com.ruoyi.framework.config.WxMaConfiguration;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.framework.web.service.WxLoginService;
import com.ruoyi.framework.web.service.WxUser;
import com.ruoyi.system.service.ISysUserCommService;
import com.ruoyi.system.service.impl.SysUserServiceImpl;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * 微信小程序用户接口
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/user/{appid}")
public class WxMaUserController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    SysUserServiceImpl userService;
    @Autowired
    SysPermissionService permissionService;
    @Autowired
    TokenService tokenService;
    @Autowired
    WxLoginService wxLoginService;
    @Autowired
    ISysCommunityService communityService;
    @Autowired
    ISysUserCommService sysUserCommService;
    /**
     * 登陆接口
     */
    @GetMapping("/login")
    public AjaxResult login(@PathVariable String appid, String code) {
        if (StringUtils.isEmpty(code)) {
            return AjaxResult.error("empty jscode");
        }

        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        try {
            WxMaJscode2SessionResult session = wxService.getUserService().getSessionInfo(code);
            this.logger.info(session.getSessionKey());
            this.logger.info(session.getOpenid());
            /**
             * 根据 openid 去数据库中查询 user 信息
             * 有则构建 LoginUser -> 存入 redis -> 返回 token
             * 没有询问用户是否 绑定已有账号
             */
            SysUser user = userService.selectUserByOpenid(session.getOpenid());

            if (StringUtils.isNotNull(user)) {
                return loginByUser(user);
            } else {
                // 首次登录 询问是否绑定已有账号
                // 返回带有 openid
                AjaxResult ajax = AjaxResult.error("请先绑定账号");
                ajax.put("openid", session.getOpenid());
                return ajax;
            }


        } catch (WxErrorException e) {
            this.logger.error(e.getMessage(), e);
            return AjaxResult.error(e.toString());
        }
    }

    @PostMapping("/create")
    public AjaxResult createUser(@RequestBody SysWxUser wxUser) {
        SysUser user = wxLoginService.createUser(wxUser);
        return loginByUser(user);
    }

    private AjaxResult loginByUser(SysUser user) {
        // 数据库中有openid绑定的账号 -> 构造 loginUser
        LoginUser loginUser = new LoginUser(user, permissionService.getMenuPermission(user));
        // 创建 token -> 创建 token 时会刷新 token，刷新过程中 缓存到了 redis
        String token = tokenService.createToken(loginUser);
        // 返回 token

        AjaxResult ajax = AjaxResult.success();
        //添加 当前社区名字
        String communityName = communityService.selectSysCommunityById(user.getCommunityId()).getName();
        ajax.put("communityName",communityName);
        //添加已认证的社区
        List<Integer> checkedComIds = sysUserCommService.selectSysUserCommDistict(user.getUserId());
//                SysUserComm cur = new SysUserComm();
//                cur.setUserId(user.getUserId());
//                cur.setCommunityId(user.getCommunityId());
//                Integer user2CommState = Integer.parseInt(sysUserCommService.selectSysUserComm(cur).getStatus());
//                if(user2CommState==null ) user2CommState=-1;
        ajax.put("checkedComs",checkedComIds);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
/*    *//**
     * <pre>
     * 获取用户信息接口
     * </pre>
     *//*
    @GetMapping("/info")
    public String info(@PathVariable String appid, String sessionKey,
                       String signature, String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密用户信息
        WxMaUserInfo userInfo = wxService.getUserService().getUserInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(userInfo);
    }

    *//**
     * <pre>
     * 获取用户绑定手机号信息
     * </pre>
     *//*
    @GetMapping("/phone")
    public String phone(@PathVariable String appid, String sessionKey, String signature,
                        String rawData, String encryptedData, String iv) {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        // 用户信息校验
        if (!wxService.getUserService().checkUserInfo(sessionKey, rawData, signature)) {
            return "user check failed";
        }

        // 解密
        WxMaPhoneNumberInfo phoneNoInfo = wxService.getUserService().getPhoneNoInfo(sessionKey, encryptedData, iv);

        return JsonUtils.toJson(phoneNoInfo);
    }*/

}
